{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn import svm, metrics\n",
    "from sklearn.datasets import fetch_openml\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# 加载MNIST数据集\n",
    "print(\"正在加载MNIST数据集...\")\n",
    "X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)\n",
    "\n",
    "# 数据预处理\n",
    "print(\"正在进行数据预处理...\")\n",
    "# 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 数据标准化\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "# 调整数据维度（如果需要）\n",
    "X_train_scaled = X_train_scaled.reshape(X_train_scaled.shape[0], -1)\n",
    "X_test_scaled = X_test_scaled.reshape(X_test_scaled.shape[0], -1)\n",
    "\n",
    "# 创建并训练SVM模型\n",
    "print(\"正在训练SVM模型...\")\n",
    "# 使用RBF核函数的SVM，C值和gamma值是重要的超参数\n",
    "clf = svm.SVC(kernel='rbf', C=10, gamma='scale', probability=True)\n",
    "clf.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 在测试集上进行预测\n",
    "print(\"正在进行模型评估...\")\n",
    "y_pred = clf.predict(X_test_scaled)\n",
    "\n",
    "# 计算并打印评估指标\n",
    "accuracy = metrics.accuracy_score(y_test, y_pred)\n",
    "print(f\"模型准确率: {accuracy:.4f}\")\n",
    "\n",
    "# 生成分类报告\n",
    "print(\"\\n分类报告:\")\n",
    "print(metrics.classification_report(y_test, y_pred))\n",
    "\n",
    "# 生成混淆矩阵\n",
    "cm = metrics.confusion_matrix(y_test, y_pred)\n",
    "print(\"\\n混淆矩阵:\")\n",
    "print(cm)\n",
    "\n",
    "# 可视化一些预测结果\n",
    "def plot_predictions():\n",
    "    plt.figure(figsize=(12, 6))\n",
    "    for i in range(10):\n",
    "        plt.subplot(2, 5, i+1)\n",
    "        # 随机选择一个样本\n",
    "        idx = np.random.randint(0, len(X_test))\n",
    "        img = X_test[idx].reshape(28, 28)\n",
    "        true_label = y_test[idx]\n",
    "        pred_label = y_pred[idx]\n",
    "\n",
    "        plt.imshow(img, cmap='gray')\n",
    "        plt.title(f'True: {true_label}\\nPred: {pred_label}')\n",
    "        plt.axis('off')\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "# 调用函数可视化预测结果\n",
    "plot_predictions()\n",
    "\n",
    "# 对单个样本进行预测的函数\n",
    "def predict_single_sample(sample_index):\n",
    "    sample = X_test[sample_index].reshape(1, -1)\n",
    "    sample_scaled = scaler.transform(sample)\n",
    "    prediction = clf.predict(sample_scaled)[0]\n",
    "    probability = clf.predict_proba(sample_scaled)[0].max()\n",
    "\n",
    "    plt.figure(figsize=(2, 2))\n",
    "    plt.imshow(X_test[sample_index].reshape(28, 28), cmap='gray')\n",
    "    plt.title(f'预测: {prediction}\\n概率: {probability:.4f}')\n",
    "    plt.axis('off')\n",
    "    plt.show()\n",
    "\n",
    "    print(f\"样本 {sample_index} 的真实标签: {y_test[sample_index]}\")\n",
    "    print(f\"模型预测标签: {prediction}\")\n",
    "    print(f\"预测概率: {probability:.4f}\")\n",
    "\n",
    "# 取消注释以下行可以测试单个样本的预测\n",
    "# predict_single_sample(42)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
